#include "adminwindow.h"

AdminWindow::AdminWindow(QWidget *parent)
    : QWidget(parent), userListModel(new QStringListModel(this)),
      recordView(new QTableView(this)), recordModel(new QStandardItemModel(this))
{
    QSplitter *splitter = new QSplitter(this);

    QListView *userListView = new QListView(splitter);
    userListView->setModel(userListModel);

    connect(userListView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &AdminWindow::onUserSelected);

    recordView->setModel(recordModel);
    splitter->addWidget(userListView);
    splitter->addWidget(recordView);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(splitter);
    setLayout(layout);

    loadUsers();
    adjustSize();
}
void AdminWindow::loadUsers() {
    QSqlQuery query("SELECT name FROM user WHERE type = 'user'");
    QStringList userList;
    while (query.next()) {
        QString username = query.value(0).toString();
        userList << username;
    }
    userListModel->setStringList(userList);
}
void AdminWindow::onUserSelected(const QModelIndex &index) {
    QString username = userListModel->data(index, Qt::DisplayRole).toString();
    loadUserRecords(username);
}
void AdminWindow::loadUserRecords(const QString &username) {
    QSqlQuery query;
    query.prepare("SELECT timestamp, caffeine FROM record WHERE name = :name");
    query.bindValue(":name", username);
    query.exec();

    recordModel->clear();
    recordModel->setHorizontalHeaderLabels({"时间", "咖啡因摄入量"});
    while (query.next()) {
        QString timestamp = query.value(0).toString();
        double caffeineIntake = query.value(1).toDouble();
        QList<QStandardItem*> rowItems;
        rowItems << new QStandardItem(timestamp) << new QStandardItem(QString::number(caffeineIntake));
        recordModel->appendRow(rowItems);
    }
}
